package com.ocean.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.SessionAware;

public class UserAction implements SessionAware,ApplicationAware{
	
	public String username;
	public Map<String, Object> session;
	public Map<String, Object> application;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	
	public String login(){
		//获取username存入session中
		session.put("username", username);
		Integer count = (Integer) application.get("count");
		if(count == null){
			count = 0;
		}
		List<String> userList = (List) application.get("userList");
		if(userList != null){
			if(!userList.contains(username)){
				userList.add(username);
				//在线人数加1
				count++;
			}
		}else{
			userList = new ArrayList();
			userList.add(username);
			count++;
		}
		application.put("userList", userList);
		application.put("count", count);
		
		return "login-success";
	}
	
	public String logout(){
		String name = (String) session.get("username");
		//在线人数减1
		List userList = (List) application.get("userList");
		if(userList != null){
			if(userList.contains(name)){
				boolean b = userList.remove(name);
				application.put("userList", userList);
				Integer count = (Integer) application.get("count");
				if(count > 0){
					count--;
				}
				application.put("count", count);
			}
		}
		//session失效
		((SessionMap)session).invalidate();
		return "logout-success";
	}

	@Override
	public void setApplication(Map<String, Object> application) {
		this.application = application;
		
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
		
	}

}
